package com.zlcode.cook.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/C")
public class CController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/run")
    public void run() {
        List<ServiceInstance> instances = discoveryClient.getInstances("waiter-service");
        for (ServiceInstance instance : instances) {
            String uri = instance.getUri().toString();
            log.info("获取到服务器地址：" + uri);
            String url = uri + "/test";
            try {
                String resp = restTemplate.getForObject(url, String.class);
                log.info(uri + " 调用服务器 test 接口成功! resp: " + resp);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("服务器： " + uri + "没有提供 test 接口.");
            }
        }
    }
}
